package com.zoo.wuhua.log;

import java.io.IOException;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.status.StatusLogger;

/**
 * Log4j2配置加载类与日志分类记录
 * 
 * @author guxue@yusys.com.cn
 * @version 2017-2-10
 */
public class EMPLog4j2Log {

    private static final Logger LOGGER = StatusLogger.getLogger();

    public void log(String message, int level, Throwable t) {
        log0("Core", level, 0, message, t);
    }

    public void log(String message, int level) {
        log0("Core", level, 0, message, (Throwable) null);
    }

    private void log0(String category, int level, int nothing, String message, Throwable t) {
        Logger logger = LogManager.getLogger(category);

        switch (level) {
        case 0:
            logger.debug(message, t);
            break;
        case 1:
            logger.trace(message, t);
            break;
        case 2:
            logger.info(message, t);
            break;
        case 3:
            logger.warn(message, t);
            break;
        case 4:
            logger.error(message, t);
            break;
        case 5:
            logger.fatal(message, t);
        }
    }

    public void init() {
        InputStream is = null;
        try {
            LOGGER.debug("加载logging.xml日志配置文件...");
            is = getClass().getResourceAsStream("/log4j2.xml");
            ConfigurationSource cs = new ConfigurationSource(is);
            Configurator.initialize(null, cs);
        } catch (IOException e) {
            LOGGER.error("初始化log4j2配置文件失败，请检查log4j2.xml配置文件", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
